<?php

namespace App\HttpController\Sys;


use App\Common\Log;
use App\Common\Sys;
use App\Common\WX\WxWord;
use App\HttpController\ControllerBase;
use App\X\EHelper;
use XWX\Common\H;

/**
 * http://php.x.siyoumi.com/test/web_0/sys/web?x_key=
 *
 * Class web
 * @package App\HttpController\sys
 */
class web extends ControllerBase
{
    public function index()
    {
        $x_key = $this->reqParam('x_key');
        $dev = $this->reqParam('dev');


        if (H::funcStrIsNullOrEmpty($x_key))
        {
            return $this->funcWriteErr(-118, '缺少key');
        }

        $data = $this->redis()->get($x_key);
        if (H::funcStrIsNullOrEmpty($data))
        {
            return $this->funcWriteErr(-128, '参数异常：key');
        }

        $json = json_decode($data, true);
        if ($json == null)
        {
            return $this->funcWriteErr(-129, '参数异常');
        }


        $is_dev = false;
        if (H::funcStrHasAnyText($dev))
        {
            $dev_code = $this->context()->redis()->get(Sys::getOauthDevKey());
            if ($dev_code == $dev)
            {
                $is_dev = true;
            }
        }

        if ($is_dev)
        {
            //调试模式
            Log::funcLogInfo(__METHOD__, '调试模式：开启');
        }
        else
        {
            //x_key只能用一次
            $this->redis()->del($x_key);
        }

        $user_id = H::funcArrayGet($json, 'getUserID');

        $word = H::funcArrayGet($json, 'word');
        $wx_wrod = new WxWord($word);

        $x = H::funcArrayGet($json, 'x');
        $this->funcSetX($x);


        //生成cookie
        $cookies = [
            'APP__user_id' => $user_id,
            'APP__x' => $this->funcGetX(),
            'APP__app_id' => $wx_wrod->app(),
            'APP__word' => $wx_wrod->content(),
            'APP__timestamp' => time(),
        ];

        $sign = Sys::funcGetSign($cookies, $this->funcGetX__config()->aconfig_app_secret);
        $cookies['APP__sign'] = $sign;

        foreach ($cookies as $k => $v)
        {
            $expire = H::now()->addMonths(60)->timestamp;
            if (EHelper::funcIsDev())
            {
                $expire = H::now()->addMonths(300)->timestamp;
            }

            $this->response()->setCookie($k, $v, $expire, "/{$wx_wrod->app()}/web_{$wx_wrod->keyNum()}");
        }


        //跳转
        //test/web_0/index
        $app_root = Sys::funcAppRoot();
        $redirect_url = "{$app_root}{$wx_wrod->app()}/web_{$wx_wrod->keyNum()}/index";


        $this->response()->redirect($redirect_url);
//        $this->commonR()->setData('redirect_url', $redirect_url);
//        $this->commonR()->setData('user', $json);
//        $this->funcWriteCommonR();
    }
}